package com.zjnu.oss.servlet;

import com.zjnu.oss.model.Admin;
import com.zjnu.oss.model.Person;
import com.zjnu.oss.model.Student;
import com.zjnu.oss.model.Teacher;
import com.zjnu.oss.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by zseapeng on 2016/7/22.
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
    private Person persontmp = new Person();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            int type = Integer.parseInt(request.getParameter("type"));
            System.out.println("type= "+type);
            Person person = new Person(username,password,type);
        System.out.println("person name=  "+person.getT_username());
            SqlSession sqlsession = null;
            sqlsession = MyBatisUtil.createSession();
        if (type == 0){
            persontmp = sqlsession.selectOne(Admin.class.getName()+".selectLogin",person);
        }else if (type == 1){
            persontmp = sqlsession.selectOne(Teacher.class.getName()+".selectLogin",person);
        }else {
            persontmp = sqlsession.selectOne(Student.class.getName()+".selectLogin",person);
        }

            MyBatisUtil.closeSqlSession(sqlsession);
            if (persontmp!=null){
                HttpSession session = request.getSession(true);
                session.setAttribute("LoginUser",persontmp);
                if (type == 0){
                    response.sendRedirect(request.getContextPath()+"/admin/admin.jsp");
                    return;
                }else if (type == 1){
                    response.sendRedirect(request.getContextPath()+"/teacher/GetStudentsServlet");
                    return;
                }else {
                    response.sendRedirect(request.getContextPath()+"/student/student.jsp");
                    return;
                }
            }else {
                response.sendRedirect(request.getContextPath()+"/error.jsp");
                return;
            }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
